

import { AttrHandler, IPropertyItem } from "../../types";
import $_ from "lodash";
import { ICmpnt, IContainerCmpnt, IContainerField } from "xcode/cmpnt";
import $data, { Column } from "xcode/data";
import { createFieldCmpnt } from "./field";
import { ref, Ref } from "vue";
import { getName } from "../bind";


function checkAndAddCmpnt(pis: IPropertyItem[], attr: IPropertyItem) {
    const labelExists = pis.some(item => item.label === attr.label);
    if (!labelExists) {
        pis.push(attr);
    }
}

// 用于构建组件的菜单属性
export const getAddCmpntAttrs: AttrHandler = (pis: IPropertyItem[], cmpnt: ICmpnt) => {
    if (!cmpnt.props.DbTable?.id) {
        return
    }
    let index = 0;
    $_.keys(cmpnt.props).forEach(key => {
        if ($_.endsWith(key.toLowerCase(), "fields") && cmpnt.props[key]) {
            index++
            let labelName = getName(key)
            labelName = labelName.length >= 4 ? labelName : `${labelName}设置`;
            var attr: IPropertyItem = { icon: "fa fa-plus", label: labelName, devided: index === 1 };
            const labelExists = pis.some(item => item.label === attr.label);
            if (labelExists || !cmpnt.props.bind?.properties) {
                return; // 如果标签已存在，则直接返回，不执行后续逻辑
            }
            attr.children = []
            getAddDbFieldPropertyItem(pis, attr, cmpnt, key);
        }
    });
}

// 获取添加数据库字段的属性项
const getAddDbFieldPropertyItem = (parent: IPropertyItem[], pis: IPropertyItem, cmpnt: ICmpnt, fieldsName: string) => {
    // 获取数据库表元数据
    $data.provider.meta.getMetaTable(cmpnt.props.DbTable.id).then((table: any) => {
        if (!table) return; // 如果没有获取到表数据，直接返回

        // 初始化检查数据对象，用于后续字段的检查操作
        const checkData: Ref<Record<string, any>> = ref({}); // 初始化检查数据对象
        $_.keys(checkData.value).forEach((key: string) => {
            checkData.value[key] = false; // 初始化检查数据对象的值为 true
        });
        cmpnt.props[fieldsName].forEach((f: any) => {
            checkData.value[f.name] = true; // 初始化检查数据对象的值为 true
        });
        if (table.columns.length > 0) {
            pis.children?.push({ icon: "fa fa-plus", label: "数据字段", group: true });
        }
        table.columns.forEach((e: Column) => {
            e.table_id = cmpnt.props.DbTable.id
            let fieldCmpnt = createFieldCmpnt(e, checkData, updateField(cmpnt as IContainerCmpnt, fieldsName));
            if (!fieldCmpnt) return; // 如果生成的字段组件为空，直接返回
            pis.children?.push(fieldCmpnt);
        });
        checkAndAddCmpnt(parent, pis);
    });
}

// 生成用于处理字段的回调函数
function updateField(cmpnt: IContainerCmpnt, fieldsName: string) {
    return function appendFields(field: IPropertyItem, isChecked: boolean) {
        let propsFields = cmpnt.props[fieldsName] as IContainerField[];

        // 如果字段未被选中，从属性字段列表中移除
        if (!isChecked) {
            let index = propsFields.findIndex(f => f.fieldId === field.dbField?.fieldId);
            if (index < 0) return; // 如果字段不存在于属性字段列表中，直接返回

            let nfield = propsFields[index];
            propsFields.splice(index, 1); // 从属性字段列表中移除字段

            // 如果字段关联了组件，移除该组件
            if (!nfield.cmpnts || !nfield.cmpnts.length) return;
            $data.func.removeCmpnt(nfield.cmpnts[0]);

        } else {
            // 如果字段被选中，且尚不存在于属性字段列表中，则添加该字段
            if (!propsFields.some(f => f.fieldId === field.dbField?.fieldId)) {
                if (!field.dbField) return;
                propsFields.push({
                    title: field.dbField?.title,
                    name: field.dbField?.name,
                    fieldId: field.dbField?.fieldId
                });

            }
        }
    }
}